﻿namespace NewsSystem.WebApi.Controllers
{
    using System;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using DropNet;
    using DropNet.Models;
    using Json;
    using NewsSystem.Contracts;
    using NewsSystem.Data;
    using NewsSystem.Models;
    using NewsSystem.Repositories;

    public class ImagesController : Controller
    {
        protected INewsUnitOfWork Uow = new NewsSystemUnitOfWork(new NewsContext());

        public string Upload(HttpPostedFileBase qqfile, string title)
        {
            if (qqfile != null)
            {
                Image image = new Image();
                this.Uow.Image.Add(image);
                this.Uow.Commit();
                string fileName = image.ImageId.ToString() + "_" + qqfile.FileName;

                string url = UploadImage(fileName, qqfile.InputStream);

                image.Url = url;
                image.Title = title;
                this.Uow.Commit();

                return JsonParser.Serialize<Image>(image);
            }

            return null;
        }

        public string Get(int id)
        {
            Image image = this.Uow.Image.Get(id);
            return string.Format("<img src='{0}' alt='{1}'>", image.Url, image.Title);
            //return JsonParser.Serialize<Image>(image);
        }

        public string Put(int id, int articleId, string title)
        {
            try
            {
                Image image = this.Uow.Image.Get(id);
                image.ArticleId = articleId;
                image.Title = title;
                Uow.Commit();
                return "Image updated!";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        public string Delete(int id)
        {
            try
            {
                this.Uow.Image.Delete(id);
                this.Uow.Commit();
                return "Image deleted!";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        private string UploadImage(string filename, System.IO.Stream imageStream)
        {
            const string apiKey = "igx0hnu6i03n576";
            const string appSecret = "7bagqisbhpswdpo";

            const string clientKey = "lk6bmes6ximfq981";
            const string clientSecret = "sgxfjbq3coss6t0";

            DropNetClient client = new DropNetClient(apiKey, appSecret, clientKey, clientSecret);

            string url = string.Empty;

            MetaData metaData = client.UploadFile("/Apps/NewsFromWoods/Images", filename, imageStream);
            url = metaData.Path;

            ShareResponse response = client.GetMedia(url);
            url = response.Url;

            return url;
        }
    }
}